/*
 * @Description:url参数相关
 * @Author: chenjiaxin
 * @Date: 2022-03-09 19:16:39
 * @LastEditTime: 2022-03-09 21:26:02
 * @FilePath: \super-unit\lib\url\index.js
 */

/**
 * url的 query解析 成对象信息
 * @param {*} url url地址  baidu.com?name=cjx&age=18&address=深圳&
 * @returns {key: value}
 */
const analyzeUrlQuery = (url) => {
  let query = {};
  if (!url.includes("?")) {
    return query;
  }
  let str = url.substring(url.indexOf("?") + 1);
  let arr = str.split("&"); // ["name=cjx", "age=18", "address=深圳", ""]
  for (let index = 0; index < arr.length; index++) {
    const element = arr[index];
    if (element) {
      let values = element.split("="); // ["name", "cjx"]
      query[values[0]] = values[1];
    }
  }
  return query;
};

/**
 * url参数解析成obj 键值对
 * @param {String} url
 * @returns
 */
const urlSearchToObj = (url) => {
  if (typeof url !== "string") {
    throw new Error("type error");
  }
  let index = url.indexOf("?");
  if (index !== -1) {
    url = url.substring(index + 1);
  }
  const urlSearch = new URLSearchParams(url);
  const iteratorObj = urlSearch.entries();
  const obj = Object.fromEntries(iteratorObj);
  return obj;
};

module.exports = {
  analyzeUrlQuery,
  urlSearchToObj
};
